<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="user_name">
        <el-input v-model="loginForm.user_name" type="text" size="large" auto-complete="off" placeholder="账号">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">记住密码</el-checkbox>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    
    <!-- 滑块验证组件 -->
    <Vcode 
      :show="showCaptcha"
      @success="handleCaptchaSuccess"
      @close="showCaptcha = false"
      :imgs="captchaImages"
    />
    
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025  All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup name="Login">
  import { loginApi } from '@/api/login'
  import { encrypt, decrypt } from '@/plugins/jsencrypt'
  import useUserStore from '@/store/modules/user'
  import { WEB_TITLE } from '@/config'

  const title = ref(WEB_TITLE)
  const userStore = useUserStore()
  const router = useRouter()
  const { proxy } = getCurrentInstance()

  onMounted(() => {
    getCache()
  })

  // 跳转到登录的链接
  const route = useRoute()
  const redirect = ref(undefined)
  watch(
    route,
    newRoute => {
      redirect.value = newRoute.query && newRoute.query.redirect
    },
    { immediate: true }
  )

  // 表单信息
  const loading = ref(false)
  const showCaptcha = ref(false)
  const loginRef = useTemplateRef('loginRef')
  const loginForm = reactive({ 
    user_name: 'admin', 
    password: 'admin123', 
    rememberMe: false, 
    captchaToken: '', 
    captchaData: null 
  })
  const loginRules = {
    user_name: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
    password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }]
  }

  // 滑块验证图片 - 使用更稳定的图片源
  const captchaImages = ref([
    'https://source.unsplash.com/random/300x150?nature,1',
    'https://source.unsplash.com/random/300x150?landscape,2',
    'https://source.unsplash.com/random/300x150?architecture,3',
    'https://source.unsplash.com/random/300x150?city,4',
    'https://source.unsplash.com/random/300x150?mountain,5',
    'https://source.unsplash.com/random/300x150?ocean,6'
  ])

  // 滑块验证成功
  function handleCaptchaSuccess(data) {
    showCaptcha.value = false
    
    // 生成验证token
    const timestamp = Date.now()
    const random = Math.random().toString(36).substring(2)
    const tokenData = `${timestamp}_${random}`
    loginForm.captchaToken = btoa(tokenData)
    loginForm.captchaData = {
      timestamp,
      verified: true
    }
    
    // 验证成功后执行登录
    doLogin()
  }

  // 登录按钮点击事件
  async function handleLogin() {
    if (loading.value) return
    if (!(await loginRef.value.validate())) return
    
    // 显示滑块验证
    showCaptcha.value = true
  }

  // 执行登录
  async function doLogin() {
    loading.value = true
    try {
      const result = await loginApi({
        user_name: loginForm.user_name,
        password: loginForm.password,
        captchaToken: loginForm.captchaToken,
        captchaData: loginForm.captchaData
      })
      
      if (loginForm.rememberMe) {
        proxy.$cache.local().set('vv__temp_user_name', loginForm.user_name, 30 * 24 * 60 * 60)
        proxy.$cache.local().set('vv__temp_password', encrypt(loginForm.password), 30 * 24 * 60 * 60)
      } else {
        proxy.$cache.local().clear('vv__temp_user_name')
        proxy.$cache.local().clear('vv__temp_password')
      }
      
      userStore
        .login(result?.token || '')
        .then(() => {
          router.push({ path: redirect.value || '/' })
        })
        .catch(err => {
          proxy.$modal.msgError(err)
        })
    } catch (error) {
      // 登录失败，清空验证信息
      loginForm.captchaToken = ''
      loginForm.captchaData = null
      proxy.$modal.msgError(error?.msg || '登录失败')
    }

    loading.value = false
  }

  // 获取缓存的数据
  function getCache() {
    const user_name = proxy.$cache.local().get('vv__temp_user_name')
    const password = proxy.$cache.local().get('vv__temp_password')
    loginForm.user_name = user_name || loginForm.user_name
    loginForm.password = password ? decrypt(password) : loginForm.password
    loginForm.rememberMe = !!user_name
  }
</script>

<style lang="scss" scoped>
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url('@/assets/images/login-background.png');
    background-size: cover;
  }
  .title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
  }

  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;
    .el-input {
      height: 40px;
      input {
        height: 40px;
      }
    }
    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 0px;
    }
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }
  
</style>
